﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Web;
using Tracy.Plugins.DownloadAdapters.ServiceDefinition;
using System.ServiceModel.Channels;
using Tracy.DataModel;
using System.Collections.Specialized;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using Tracy.DataModel.DownloadAdapter;
using SharedLib;
using Tracy.DataModel.Config;
using SharedLib.WinFormMVCFramework;
using Tracy.Plugins.DownloadAdapters.Model;

namespace Tracy.Plugins.DownloadAdapters
{
    public partial class UTorrentAdapter : IDownloadAdapter, IConfigurable
    {
        public event EventHandler<DataChangedEventArgs<IConfigModel>> ConfigChanged;

        internal event EventHandler<DataChangedEventArgs<IConfigModel>> ConfigUpdated;

        UTorrentConfiguration _currentConfig = null;

        internal void TestConfig(IConfigModel config)
        {
            if (Process.GetProcessesByName("uTorrent").Length == 0)
            {
                Process.Start(_applicationFullPath);
                System.Threading.Thread.Sleep(2000);
            }

            UTorrentWebUIClient testClient = new UTorrentWebUIClient();
            testClient.LoadConfig((UTorrentConfiguration)config);
            //_initFailedFlag = false;
        }

        internal void UpdateConfig(IConfigModel originalConfig, IConfigModel config)
        {
            
            ConfigChanged.InvokeEvent(this, new DataChangedEventArgs<IConfigModel>(originalConfig, config));
            //TODO: move to another public function, to be called by tracy
            _currentConfig = (UTorrentConfiguration)config;
            _utClient.Reset();
            //_initFailedFlag = false;
            
            ConfigUpdated.InvokeEvent(this, new DataChangedEventArgs<IConfigModel>(originalConfig, config));
        }

        public IConfigModel LoadConfig(UTorrentConfiguration config)
        {
            if (config != null)
            {
                _currentConfig = config;
                //_initFailedFlag = false;
                return _currentConfig;
            }
            return null;
        }

        public IConfigModel LoadConfig(XmlNode configNode)
        {
            return LoadConfig(new UTorrentConfiguration(configNode));
        }

        public string Name
        {
            get;
            set;
        }


        public IController<IConfigView> CreateConfigViewController()
        {
            UTorrentConfigViewController controller = new UTorrentConfigViewController(this);
            ConfigUpdated.InvokeEvent(this, new DataChangedEventArgs<IConfigModel>(null, _currentConfig));
            return controller;
        }
    }
}